<template>
    <div class="koi-flex">
        <KoiCard>
            <!-- 搜索条件 -->
            <el-form @submit.native.prevent v-show="showSearch" :inline="true">
                <el-form-item label="标签名" prop="categoryName">
                    <el-input placeholder="请输入标签名" v-model="searchParams.categoryName" clearable style="width: 240px"
                        @keyup.enter.native="handleListPage"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
                    <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 表格头部按钮 -->
            <el-row :gutter="10">
                <el-col :span="1.5" v-auth="['system:role:delete']">
                    <el-button type="danger" icon="delete" plain @click="handleBatchDelete()"
                        :disabled="multiple">删除</el-button>
                </el-col>
                <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
            </el-row>

            <div class="h-20px"></div>
            <!-- 数据表格 -->
            <el-table v-loading="loading" border :data="tableList" empty-text="暂时没有数据哟🌻"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" prop="categoryId" width="120px" align="center"
                    type="index"></el-table-column>
                <el-table-column label="标签名" prop="categoryName" :show-overflow-tooltip="true"
                    align="center"></el-table-column>
                <el-table-column label="关联文章" prop="tagLinkTitle" width="180px" align="center">
                    <template #default="{ row }">
                        <el-button circle type="primary" plain @click="handleTagLinkTitle(row)"
                            :disabled="row.tagLinkTitle.length == 0">
                            {{ row.tagLinkTitle.length }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
                <el-table-column label="修改时间" prop="createTime" width="180px" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-tooltip content="删除🌻" placement="top">
                            <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                                v-auth="['system:role:delete']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <div class="h-20px"></div>
            <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
                v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleListPage" @current-change="handleListPage" />
        </KoiCard>

        <!-- 添加 OR 修改对话框 -->
        <KoiDialog ref="koiDialogRef" :title="title" :confirmLoading="confirmLoading" :footerHidden="true">
            <template v-if="text" #header>
                <el-button class="" type="primary" icon="Back" plain @click="text = ''">返回目录</el-button>
            </template>
            <template #content>
                <div v-if="text">
                    <v-md-preview :text="text"></v-md-preview>
                </div>
                <div v-else v-for="articleTitleItem in articleTitle" :key="articleTitleItem">
                    <el-link type="primary" @click="getArticle(articleTitleItem)">{{ articleTitleItem.title }}</el-link>
                    <el-divider class="mt-[6px] mb-[6px]" />
                </div>
            </template>
        </KoiDialog>

    </div>
</template>

<script setup lang="ts" name="rolePage">
import { ref, onMounted } from "vue";
// @ts-ignore
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
// @ts-ignore
import { listPage, getById, add, update, deleteById, batchDelete, updateStatus } from "@/api/system/role/index.ts";
import { getTagList, deleteTag } from "@/api/system/tag";
import { getArticleByTitle } from "@/api/system/article";
// 展示文章标题
const articleTitle = ref();
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>();
// text
const text = ref<string>("");


// 查询参数
const searchParams = ref({
    page: 1, // 第几页
    pageSize: 10, // 每页显示多少条
    categoryName: "",
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
    searchParams.value = {
        page: 1,
        pageSize: 10,
        categoryName: "",
    };
};

/** 搜索 */
const handleSearch = () => {
    console.log("搜索");
    searchParams.value.page = 1;
    handleListPage();
};

/** 重置 */
const resetSearch = () => {
    console.log("重置搜索");
    resetSearchParams();
    handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
    total.value = 9;
    try {
        loading.value = true;
        tableList.value = []; // 重置表格数据
        const res: any = await getTagList(searchParams.value);
        tableList.value = res.data.records;
        total.value = res.data.total;
        loading.value = false;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
    try {
        const res: any = await getTagList(searchParams.value);
        tableList.value = res.data.records;
        total.value = res.data.total;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    }
};

onMounted(() => {
    // 获取表格数据
    handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
    console.log(selection);
    ids.value = selection.map((item: any) => item.categoryId);
    single.value = selection.length != 1; // 单选
    multiple.value = !selection.length; // 多选
};
// 展示相关文章标题
const handleTagLinkTitle = (row: any) => {
    koiDialogRef.value.koiOpen();
    articleTitle.value = row.tagLinkTitle;
    text.value = "";
};
// 获取相关文章
const getArticle = async (item:any) => {
    try {
        const res: any = await getArticleByTitle(item.articleId);
        text.value = res.data;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据获取失败，请刷新重试🌻");
    }
};

// 添加 OR 修改对话框Ref 
const koiDialogRef = ref();
// 标题
const title = ref("相关文章");


// 确定按钮是否显示Loading
const confirmLoading = ref(false);
/** 删除 */
const handleDelete = (row: any) => {
    const id = row.categoryId;
    if (id == null || id == "") {
        koiMsgWarning("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要删除标签[" + row.categoryName + "]么？")
        .then(async () => {
            try {
                await deleteTag([id]);
                handleTableData();
                koiNoticeSuccess("删除成功🌻");
            } catch (error) {
                console.log(error);
                koiNoticeError("删除失败，请刷新重试🌻");
                handleTableData();
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};

/** 批量删除 */
const handleBatchDelete = () => {
    if (ids.value.length == 0) {
        koiMsgInfo("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要进行批量删除么？")
        .then(async () => {
            try {
                // console.log("ids",ids.value)
                await deleteTag(ids.value);
                handleTableData();
                koiNoticeSuccess("批量删除成功🌻");
            } catch (error) {
                console.log(error);
                koiNoticeError("批量删除失败，请刷新重试🌻");
                handleTableData();
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};
</script>

<style lang="scss" scoped></style>
